extends Node2D

const s_barrier = preload("res://res/entity/barrier.tscn")
@onready var helicopter: CharacterBody2D = %Helicopter
@onready var replay_game: Control = $replay_game
@onready var start_menu: Control = $start_menu
@onready var background_music: AudioStreamPlayer = $background_music
@onready var death_sound: AudioStreamPlayer = $death_sound
@onready var windows_size = get_viewport_rect()
var waiting_for_input :bool = false
var timer :Timer = Timer.new()


func _ready() -> void:
	helicopter.visible = false
	replay_game.visible = false
	get_tree().paused = true
	

func _process(delta: float) -> void:
	#检测牢大是否超出屏幕
	var helicopter_position_y= helicopter.position.y
	if helicopter_position_y<0 or helicopter_position_y>=windows_size.size.y:
		game_over()

func creat_barrier()->void:
	var building = s_barrier.instantiate()
	building.add_to_group("barrier")
	var up_or_down :int = randi_range(0,1)
	if up_or_down:
		building.position = Vector2(1431,randi_range(Gs.up_barrier_range.x,Gs.up_barrier_range.y))
	else:
		building.rotation_degrees = 180
		building.position = Vector2(1414,randi_range(Gs.down_barrier_range.x,Gs.down_barrier_range.y))
		
	building.crashed.connect(_on_barrier_crashed)
	self.add_child(building)
	
func restart_game()->void:
	helicopter.visible = true
	start_menu.visible = false
	replay_game.visible = false
	helicopter.position = Vector2(186,355)
	helicopter.velocity.y = 0
	helicopter.rotation_degrees = 0
	get_tree().paused = false
	timer.timeout.connect(_on_timer_timeout)
	timer.wait_time = randf_range(Gs.min_wait_time,Gs.max_wait_time)
	self.add_child(timer)
	timer.start()


	
func game_over()->void :
	replay_game.visible = true
	print("game_over")
	#暂停游戏
	get_tree().paused = true
	#让牢大和楼房一起全部消失
	#helicopter.queue_free()
	for a in get_tree().get_nodes_in_group('barrier'):
		a.queue_free()

func _on_barrier_crashed()->void:
	print("牢牢大坠机了")
	game_over()
	
func _on_timer_timeout()->void:
	creat_barrier()
	timer.wait_time = randf_range(Gs.min_wait_time,Gs.max_wait_time)
	print("创建障碍时间：",timer.wait_time)
	timer.start()
	
func _on_replay_game_quit() -> void:
	get_tree().quit()

func _on_replay_game_retry() -> void:
	restart_game()

func _on_start_menu_start() -> void:
	restart_game()

func _input(event: InputEvent) -> void:
	pass
